package com.teamwork.shareplatform.controller;

import com.teamwork.shareplatform.entity.Subject;
import com.teamwork.shareplatform.service.SubjectService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class SubjectController {
    private static final Logger logger = LoggerFactory.getLogger(SubjectController.class);

    @Autowired
    private SubjectService subjectService;

    @GetMapping({"/user/subjects"})
    public CommonResult<List<Subject>> getSubjects() {
        try {
            List<Subject> subjects = subjectService.queryAll();
            return buildSuccessResult(subjects, "获取成功");
        } catch (Exception e) {
            return handleException(e, "获取科目列表时出现异常", "获取科目列表失败");
        }
    }

    @GetMapping({"/user/subjectlist"})
    public CommonResult<Map<String, List<Subject>>> getSubjectList() {
        try {
            List<Subject> subjectList = subjectService.queryByLevel();
            Map<String, List<Subject>> maps = new HashMap<>();

            for (Subject subject : subjectList) {
                List<Subject> subjectChild = subjectService.queryByParent(subject.getId());
                maps.put(subject.getName(), subjectChild);
            }

            return buildSuccessResult(maps, "获取成功");
        } catch (Exception e) {
            return handleException(e, "获取科分层列表时出现异常", "获取科分层列表失败");
        }
    }

    private <T> CommonResult<T> buildSuccessResult(T data, String message) {
        CommonResult<T> commonResult = new CommonResult<>();
        commonResult.setCode(200);
        commonResult.setMessage(message);
        commonResult.setData(data);
        return commonResult;
    }

    private <T> CommonResult<T> handleException(Exception e, String logMessage, String errorMessage) {
        logger.error(logMessage, e);
        CommonResult<T> errorResult = new CommonResult<>();
        errorResult.setCode(-1);
        errorResult.setMessage(errorMessage);
        return errorResult;
    }
}